package org.study.bookmanager.service.impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.study.bookmanager.entity.Users;
import org.study.bookmanager.repo.UsersRespository;

import java.util.ArrayList;

@Service
@Slf4j
public class JwtUserDetailsServiceImpl implements UserDetailsService {

    @Resource
    UsersRespository usersRespository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("loadUserByUsername: " + username);
        Users user = usersRespository.findPasswordByuserName(username);
        log.info("user: " + user);

        if (user == null) {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }

        // 构建 UserDetails 对象
        UserDetails userDetails = User.builder()
                .username(username)
                .password(user.getPasswordHash())
                .authorities(new ArrayList<>())  // 这里可以设置用户的权限信息，可以根据实际情况设置
                .build();

        return userDetails;
    }
}